package cn.z2huo.usercenter.management.app.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.text.SimpleDateFormat;

/**
 * <p>
 *
 * @author z2huo
 */
@Configuration
public class JacksonConfig {

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();

        // 序列化配置

        // 处理 jsr310 的时间
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        // 将 JSON 输出格式化为缩进格式
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        // 忽略 null 值
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // 将枚举输出为名称
        objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, false);

        // 反序列化配置

        // 反序列化时忽略 JSON 存在但 Java 类中不存在的属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 不允许 JSON 中的字段名不带引号
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, false);
        // 不允许单引号
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, false);
        // 不允许注释
        objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, false);


        return objectMapper;
    }

}
